<template>
  <div class="admin-layout">
    <el-container>
      <!-- 左侧菜单栏 -->
      <el-aside :width="isCollapse ? '64px' : '240px'" class="sidebar">
        <div class="logo-container">
          <div v-if="!isCollapse" class="logo-full">
            <el-icon :size="28" color="#409EFF"><TrendCharts /></el-icon>
            <span class="logo-text">热搜AI系统</span>
          </div>
          <el-icon v-else :size="28" color="#409EFF"><TrendCharts /></el-icon>
        </div>

        <el-menu
          :default-active="activeMenu"
          :collapse="isCollapse"
          :collapse-transition="false"
          background-color="#001529"
          text-color="rgba(255, 255, 255, 0.65)"
          active-text-color="#409EFF"
          class="sidebar-menu"
          router
        >
          <el-menu-item index="/dashboard">
            <el-icon><Odometer /></el-icon>
            <template #title>控制台</template>
          </el-menu-item>

          <el-sub-menu v-if="showSystemMenu" index="system">
            <template #title>
              <el-icon><Setting /></el-icon>
              <span>系统设置</span>
            </template>
            <el-menu-item v-if="canViewUsers" index="/system/users">用户管理</el-menu-item>
            <el-menu-item v-if="canViewRoles" index="/system/roles">角色权限</el-menu-item>
            <el-menu-item v-if="canViewConfigs" index="/system/configs">系统配置</el-menu-item>
            <el-menu-item v-if="canViewLogs" index="/system/logs">操作日志</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>

      <!-- 右侧主内容区 -->
      <el-container class="main-container">
        <!-- 顶部导航栏 -->
        <el-header class="top-header">
          <div class="header-left">
            <el-icon class="collapse-icon" @click="toggleCollapse" :size="20">
              <Fold v-if="!isCollapse" />
              <Expand v-else />
            </el-icon>
            <el-breadcrumb separator="/">
              <el-breadcrumb-item>首页</el-breadcrumb-item>
              <el-breadcrumb-item>{{ currentPageTitle }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>

          <div class="header-right">
            <div class="notification-wrapper">
              <el-icon :size="20" class="notification-icon"><Bell /></el-icon>
            </div>

            <el-dropdown @command="handleCommand" class="user-dropdown">
              <span class="user-info">
                <el-avatar :size="32">
                  <el-icon><User /></el-icon>
                </el-avatar>
                <span class="username">{{ userStore.userInfo?.username || '管理员' }}</span>
                <el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item disabled>
                    <el-icon><User /></el-icon>
                    {{ userStore.userInfo?.is_superuser ? '超级管理员' : '管理员' }}
                  </el-dropdown-item>
                  <el-dropdown-item divided command="profile">
                    <el-icon><Setting /></el-icon>
                    个人设置
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">
                    <el-icon><SwitchButton /></el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        
        <!-- 主内容区 - 路由视图 -->
        <el-main class="dashboard-main">
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { hasPermission } from '../utils/permission'
import { 
  User,
  ArrowDown,
  SwitchButton,
  TrendCharts,
  Setting,
  Odometer,
  Fold,
  Expand,
  Bell
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 菜单折叠状态
const isCollapse = ref(false)

// 当前激活的菜单（根据路由路径自动计算）
const activeMenu = computed(() => {
  return route.path
})

// 当前页面标题（从路由meta中获取）
const currentPageTitle = computed(() => {
  return route.meta.title || '控制台'
})

// 菜单权限控制
const canViewUsers = computed(() => {
  const result = hasPermission('user.view')
  console.log('canViewUsers:', result)
  return result
})

const canViewRoles = computed(() => {
  const result = hasPermission('role.view')
  console.log('canViewRoles:', result)
  return result
})

const canViewConfigs = computed(() => {
  const result = hasPermission('config.view')
  console.log('canViewConfigs:', result)
  return result
})

const canViewLogs = computed(() => {
  const result = hasPermission('log.view')
  console.log('canViewLogs:', result)
  return result
})

// 是否显示系统设置菜单（至少有一个子菜单可见）
const showSystemMenu = computed(() => {
  const result = canViewUsers.value || canViewRoles.value || canViewConfigs.value || canViewLogs.value
  console.log('showSystemMenu:', result, {
    canViewUsers: canViewUsers.value,
    canViewRoles: canViewRoles.value,
    canViewConfigs: canViewConfigs.value,
    canViewLogs: canViewLogs.value
  })
  return result
})

// 切换侧边栏折叠
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 处理下拉菜单命令
const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await userStore.logout()
      ElMessage.success('退出登录成功')
      router.push('/login')
    } catch (error) {
      if (error !== 'cancel') {
        console.error('退出登录失败:', error)
      }
    }
  } else if (command === 'profile') {
    ElMessage.info('个人设置功能开发中...')
  }
}

// 组件挂载时获取用户信息（每次都刷新以获取最新权限）
onMounted(async () => {
  // 强制刷新用户信息，确保权限是最新的
  await userStore.fetchUserInfo()
  console.log('用户信息已刷新:', userStore.userInfo)
  console.log('用户权限:', userStore.userInfo?.permissions)
})
</script>

<style scoped>
/* 整体布局 */
.admin-layout {
  height: 100vh;
  overflow: hidden;
}

.admin-layout .el-container {
  height: 100%;
}

/* 侧边栏样式 */
.sidebar {
  background-color: #001529;
  transition: width 0.3s;
  overflow-x: hidden;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #002140;
  margin-bottom: 10px;
}

.logo-full {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-text {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.sidebar-menu {
  border-right: none;
  height: calc(100vh - 70px);
  overflow-y: auto;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 240px;
}

/* 确保菜单文字颜色正确 */
.sidebar-menu :deep(.el-menu-item),
.sidebar-menu :deep(.el-sub-menu__title) {
  color: rgba(255, 255, 255, 0.65) !important;
}

.sidebar-menu :deep(.el-menu-item:hover),
.sidebar-menu :deep(.el-sub-menu__title:hover) {
  background-color: rgba(255, 255, 255, 0.08) !important;
  color: #fff !important;
}

.sidebar-menu :deep(.el-menu-item.is-active) {
  color: #409EFF !important;
  background-color: rgba(64, 158, 255, 0.1) !important;
}

.sidebar-menu :deep(.el-sub-menu .el-menu-item) {
  background-color: #000c17 !important;
}

.sidebar-menu :deep(.el-sub-menu .el-menu-item:hover) {
  background-color: rgba(255, 255, 255, 0.08) !important;
}

/* 主容器 */
.main-container {
  background-color: #f0f2f5;
  height: 100vh;
  overflow: hidden;
}

/* 顶部导航栏 */
.top-header {
  background: white;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 60px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.collapse-icon {
  cursor: pointer;
  transition: all 0.3s;
}

.collapse-icon:hover {
  color: #409EFF;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 24px;
}

.notification-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.notification-wrapper:hover {
  background-color: #f5f7fa;
}

.notification-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
}

.notification-wrapper:hover .notification-icon {
  color: #409EFF;
}

.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f7fa;
}

.username {
  font-size: 14px;
  color: #333;
}

/* 主内容区 */
.dashboard-main {
  height: calc(100vh - 60px);
  overflow-y: auto;
  padding: 0;
  background-color: #f0f2f5;
}

/* 响应式 */
@media (max-width: 768px) {
  .top-header {
    padding: 0 16px;
  }

  .username {
    display: none;
  }
}
</style>

